<?php
/**
 * Task Edition Box.
 * To update or add a new task
 *
 * @package tasks
 *
 * @author Xavier VILAIN
 */
use Hive\Company;
use Shama\Task\Reference;
use Fox\Generator;
use Shama\Task;
use Fox\Html\Screen,Fox\Popup;

$xview = Xview::instance();
$popup =  $xview->val('popup');
$tid =  $xview->val('taskid');
$objId =  $xview->val('reference');
$execute =  $xview->val('execute');
// load tasks
try {
	$task = new Task($tid);
}
catch (Fox\Object\Exception\NotExist $e)
{
	$task = new Task();
}
if($task->exists()) {
	$action = 'update';
} else {
	$action = 'add';
}
$data = $task->getData();

$screen = new Screen('sTask',$action,null,true,Generator::ajaxReload('contentCol',
			Generator::url('company','tasks',null,array('cpid' => $objId))));

$block = $xview->component('task','info');
$block->remove('reference_id');
$block->noLegend();

if(!$task->exists()) {
	$block->item('status')->input(false);
}
$screen->add($block);
$screen->initialize($data);

if($screen->submitted())
{
	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			if($task->exists()) {
				$task->setFields($fields);
				$task->prepareUpdate(Task::CHANGE_DEFAULT);
				$task->update();
				Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_UPDATE,$task->subject));
			} else {
				$fields['auto'] = 0;
				$task->setFields($fields);
				// Add Object References
				$reference = new Reference();
				$reference->setFields(array(
					'reference' => Company::TASK_REFERENCE,
					'reference_id' => $objId
				));
				$task->addToReferences($reference);
				$task->create();
				Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE,$task->subject));
			}
			// Add User as a reference ?
			//@TODO handle multiple user
		}
		catch (Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e->getMessage());
		}
	}
	return $xview->messages(true,true);
	exit;
}

$title = Msg(Hive::BUNDLE,Hive::TASK_ADD);
$popup = new Popup('pTask',$title,$screen,800);
echo $popup->display();